<!--淘宝自动上架模块-->

<template>
  <div>
    <TableSearch :query="queryParams" :options="searchOpt" :search="handleSearchEvent"/>
    <div class="container">
      <TableCustom :columns="columns" :tableData="tableData" :total="page.total" :viewFunc="handleView"
                   :delFunc="handleDelete" :editFunc="handleEditEvent" :refresh="refreshPageEvent"
                   :currentPage="page.index"
                   :page-size="page.size"
                   :changePage="changePage"
                   :delSelection="delSelectionAccountsEvent"
                   :pageSizeChange="handleSizeChange"
                   :has-toolbar="true"
                   @selection-change="selectRowChanged"
                   :has-pagination="true">
        <template #toolbarBtn>
          <!--          <el-button type="warning" :icon="CirclePlusFilled" @click="visible = true">新增</el-button>-->
          <el-button type="warning" :icon="CirclePlusFilled" @click="visible = true" title="添加">添加
          </el-button>

          <el-button type="success" :icon="CirclePlusFilled" @click="exportXlsx" title="导出当前页或者所选">导出
          </el-button>
        </template>

        <template #money="{ rows }">
          ￥{{ rows.money }}
        </template>
        <template #thumb="{ rows }">
          <el-image class="table-td-thumb" :src="rows.thumb" :z-index="10" :preview-src-list="[rows.thumb]"
                    preview-teleported>
          </el-image>
        </template>
        <template #state="{ rows }">
          <el-tag :type="rows.state ? 'success' : 'danger'">
            {{ rows.state ? '正常' : '异常' }}
          </el-tag>
        </template>

        <template #operator="{ rows, index }">
          <template v-if="!rows.editing">
            <el-space>
              <el-button type="primary" size="small" :icon="Edit" @click="handleEditEvent(rows)" v-show="false">
                编辑
              </el-button>

              <el-switch v-model="rows.accountStatus" active-value="启用" inactive-value="禁用"
                         title="切换状态"
                         @change="updateAccountStatusEvent(rows)">
                <template #active-action>
                  <span class="custom-active-action">E</span>
                </template>
                <template #inactive-action>
                  <span class="custom-inactive-action">T</span>
                </template>
              </el-switch>

              <el-popconfirm
                  confirm-button-text="Yes"
                  cancel-button-text="No"
                  :icon="InfoFilled"
                  icon-color="#626AEF"
                  title="重新购买游戏"
                  @confirm="confirmReBuy(rows)"
              >
                <template #reference>
                  <el-button type="success" size="small" :icon="ShoppingTrolley" title="重新购买游戏">
                  </el-button>
                </template>
              </el-popconfirm>

              <el-button type="primary" title="下载日志" size="small" :icon="Download" @click="DownloadLog(rows)">

              </el-button>
              <el-popconfirm
                  confirm-button-text="Yes"
                  cancel-button-text="No"
                  :icon="InfoFilled"
                  icon-color="#626AEF"
                  title="确定删除这条数据吗"
                  @confirm="confirmDeleteEvent(rows)"
              >
                <template #reference>
                  <el-button type="danger" size="small" :icon="Delete" title="删除">

                  </el-button>
                </template>
              </el-popconfirm>


            </el-space>
          </template>
          <template v-else>
            <el-button type="success" size="small" :icon="Select" @click="rows.editing = false">
              保存
            </el-button>
            <!--            <el-button type="default" size="small" :icon="CloseBold" @click="handleCancel(rows, index)">-->
            <!--              取消-->
            <!--            </el-button>-->
          </template>
        </template>

      </TableCustom>

    </div>
    <!--
      编辑事件
    -->
    <el-dialog :title="isEdit ? '编辑' : '新增'" v-model="visible" width="700px" destroy-on-close
               :close-on-click-modal="false" @close="closeDialog">
      <TableEdit :form-data="rowData" :options="editOptions" :edit="isEdit" :update="updateDataEvent" :cancel="cancelOperation">
        <template #thumb="{ rows }">
          <img class="table-td-thumb" :src="rows.thumb"></img>
        </template>
      </TableEdit>
    </el-dialog>
    <!--
      导入账号和令牌弹窗
    -->
    <el-dialog title="导入账号" v-model="importVisible" width="700px" destroy-on-close
               :close-on-click-modal="false" @close="closeDialog">
      <TableEdit :form-data="rowData" :options="importOption" :edit="isEdit" :update="importAccountEvent"
                 :cancel="cancelOperation">
        <template #thumb="{ rows }">
          <img class="table-td-thumb" :src="rows.thumb"></img>
        </template>
      </TableEdit>

    </el-dialog>
    <el-dialog title="查看详情" v-model="visible1" width="700px" destroy-on-close>
      <TableDetail :data="viewData">
        <template #thumb="{ rows }">
          <el-image :src="rows.thumb"></el-image>
        </template>
      </TableDetail>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="tbModel">

import {getCurrentInstance, onMounted, reactive, ref} from 'vue';
import {ElMessage, ElMessageBox,} from 'element-plus';
import {
  CirclePlusFilled,
  Delete,
  Download,
  Edit,
  InfoFilled,
  Select,
  ShoppingTrolley
} from '@element-plus/icons-vue';
import TableCustom from '@/components/table-custom.vue';
import TableDetail from '@/components/table-detail.vue';
import TableSearch from '@/components/table-search.vue';
import {FormOption, FormOptionList} from '@/types/form-option';
import {GameShopItem} from "@/types/shopManageItem";
import {TbModel} from "@/types/tbModel";

import {exportToXlsx} from "@/utils/exportUtils";

const api = getCurrentInstance()?.appContext.config.globalProperties.$api;

/**
 *
 *
 *  test
 * common part
 * **/

// 查询相关
const queryParams = reactive({
  serial: null,
  uploadStatus: null,
  productType: null,
  pageSize: 10,
  currentPage: 1,
});

const page = reactive({
  index: 1,// currentPage
  size: 10, // pageSize
  total: 200, //totalCount
})
/**
 * constant area
 * */
const tableData = ref<GameShopItem[]>([]);
const selectRows = ref([])

const visible = ref(false);
const isEdit = ref(false);
const rowData = ref({});
/**
 * 导入弹出框
 * */
const importVisible = ref(false)
/**
 * 页面加载的时候加载数据
 *
 * */
// 查看详情弹窗相关
const visible1 = ref(false);
const viewData = ref({
  row: {},
  list: []
});
/**
 *  function area
 *
 * **/
onMounted(() => {
  getAccountDataList();
})

const handleSearchEvent = () => {
  page.index = 1;
  queryParams.currentPage = 1;
  queryParams.pageSize = page.size;
  getAccountDataList(false, false);
};

const selectRowChanged = (rows) => {
  selectRows.value = rows;
}


/**
 * 页码改变事件
 * */
const changePage = (val: number) => {
  page.index = val;
  queryParams.currentPage = val;
  queryParams.pageSize = page.size;
  getAccountDataList(false, true);
};

/**
 *
 * edit row event
 *
 * **/
const handleEditEvent = (row: TbModel) => {
  rowData.value = {...row};
  isEdit.value = true;
  visible.value = true;
};
/**
 * 页数大小改变事件
 * */
const handleSizeChange = (val: number) => {
  page.index = 1;
  page.size = val;
  queryParams.currentPage = val;
  queryParams.pageSize = page.size;
};

const confirmDeleteEvent = (row) => {
}

const delSelectionAccountsEvent = (val: GameShopItem[]) => {
  ElMessageBox.confirm(
      '确定删除这些记录吗',
      'Warning',
      {
        confirmButtonText: 'OK',
        cancelButtonText: 'Cancel',
        type: 'warning',
      }
  )
      .then(() => {
        deleteAccounts(val.map(e => ({id: e.id})))
      })
      .catch(() => {

      })
}

/**
 * 刷新按钮事件
 *
 * */
const refreshPageEvent = () => {

  getAccountDataList(true, false);
}


/**
 * upload file changed event
 * */
const uploadDataChangedEvent = async (event, fileList) => {
  if (fileList.length > 1) {
    fileList.splice(0, 1);
  }

}



/**
 * 处理点击删除操作事件
 * */
const handleDeleteEvent = async (row: GameShopItem) => {
  let data = {
    id: row.id
  }

}



/***
 * 新增/编辑操作
 */
const updateDataEvent = async (value) => {
  closeDialog();
  getAccountDataList();
};

// 删除相关
const handleDelete = (row: GameShopItem) => {
  ElMessage.success('删除成功');
  console.log(row)
}
/**
 *
 * 取消操作
 * **/
const cancelOperation = () => {
  closeDialog();
}



const importDataEvent = async (value) => {
  ElMessage.success("正在导入中,请稍后刷新页面查询结果")
  importVisible.value = false
}

const closeDialog = () => {
  visible.value = false;
  isEdit.value = false;
  importVisible.value = false;
};


const confirmReBuy = (row) => {
  let param = {
    id: row.id
  }
  api.post("/api/account/rePurchaseGameGame", param, (res) => {
    ElMessage.success(res.msg)
  })
}

const exportXlsx = () => {
  let data = selectRows.value;
  if (selectRows.value.length == 0) {
    data = tableData.value
  }
  if (data.length == 0) {
    ElMessage.info("没有数据可导出")
    return
  }
  exportToXlsx(data, columns.value, "账号")
};

const updateAccountStatusEvent = (row) => {
  let params = {
    "id": row.id,
    status: row.accountStatus == '启用' ? 1 : 0
  }
  api.post("/api/account/updateStatus", params, (res => {
    if (res.code == 1) {
      ElMessage.success("更新成功")
      row.status = params.status;
    } else {
      ElMessage.error("更新失败")
      row.accountStatus = params.status == 1 ? '禁用' : '启用'
    }
  }))
}

const getAccountDataList = async (isRefresh = false, isPage = false) => {
  console.log(isRefresh ? {} : queryParams)
  tableData.value = [
    {
      winSerial: 1,
      productType: '手机壳',
      rowNo: '4',
      runStatus: "运行中"
    }, {
      winSerial: 1,
      productType: '手机壳',
      rowNo: '5',
      runStatus: "运行中"
    }, {
      winSerial: 1,
      productType: '手机壳',
      rowNo: '6',
      runStatus: "运行中"
    }, {
      winSerial: 1,
      productType: '手机壳',
      runStatus: "运行中"
    },
  ]
  // api.post("/api/account/findList", isRefresh ? {} : queryParams, (res) => {
  //   tableData.value = res.data;
  //   if (!isPage) {
  page.total = 10;
  //   }
  // })
};


const handleView = (row: GameShopItem) => {
  viewData.value.row = {...row}
  viewData.value.list = [
    {
      prop: 'id',
      label: '用户ID',
    },
    {
      prop: 'gameId',
      label: '游戏ID',
    },
    {
      prop: 'accountName',
      label: '账号',
    },
    {
      prop: 'password',
      label: '密码',
    }, {
      prop: 'makFile',
      label: '令牌',
    },
    {
      prop: 'currency',
      label: '币种',
    }, {
      prop: 'currentBalance',
      label: '当前余额',
    },
  ]
  visible1.value = true;
};


// 下载日志
const DownloadLog = async (row: GameShopItem) => {
  api.get("/api/log/download?id=" + row.id, {}, (res) => {
    console.log(res)
    // 创建Blob对象
    const blob = new Blob([res.data], {type: 'application/octet-stream'});
    let downloadUrl = URL.createObjectURL(blob);
    let a = document.createElement("a");
    a.href = downloadUrl;
    a.download = row.id + ".log"; // 指定下载文件名
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(downloadUrl); // 释放URL对象
  })
}


/**
 * 表格字段区域
 *
 * */
const searchOpt = ref<FormOptionList[]>([

  {
    type: 'select',
    label: '上架状态:',
    prop: 'uploadStatus',
    width: 100,
    opts: [{"value": "1", "label": "成功"}, {"value": "0", "label": "失败"}]
  }, {
    type: 'select',
    label: '产品类别:',
    prop: 'productType',
    width: 100,
    opts: [{"value": "1", "label": "成功"}, {"value": "0", "label": "失败"}]
  },

  {type: 'input', label: '序号：', prop: 'winSerial', marginLeft: "30px",},
])
// 表格相关
let columns = ref([
  {type: 'selection'},
  {type: 'index', label: '序号', width: 55, align: 'center'},
  {prop: 'winSerial', label: '窗口序号', width: 105, align: 'center'},
  {prop: 'id', label: 'Id', visible: false},
  {prop: 'productType', label: '产品类别', width: 100},
  {prop: 'rowNo', label: '行号', width: 100},
  {prop: 'runStatus', label: '运行状态', width: 100},
  {prop: 'operator', label: '操作', width: 180, fixed: "right"},
])
// 新增/编辑弹窗相关
let editOptions = ref<FormOption>({
  labelWidth: '500px',
  span: 128,
  list: [
    {type: 'input', label: '账号', prop: 'accountName', required: true},
    {type: 'input', label: '密码', prop: 'password', required: true},
    {
      type: 'switch', label: 'makFile', prop: 'makFile', activeText: '是', inactiveText: '否', activeValue: 1,
      inactiveValue: 0, required: false
    },
    {type: 'input', label: '币种', prop: 'currency', required: true},
    {type: 'select', label: '游戏ID', prop: 'gameId', required: false, placeholder: "购买的商品游戏"},
    {type: 'select', label: '礼物ID', prop: 'giftId', required: false, placeholder: "送礼物商品ID"},
    {type: 'select', label: '好友', prop: 'receivedGiftUserId', required: false, placeholder: "送礼给好友"},
    {
      type: 'switch', activeText: '启用', inactiveText: '禁用', label: '账号状态', activeValue: 1,
      inactiveValue: 0, prop: "status", required: false
    },
    // { type: 'upload', label: '头像', prop: 'thumb', required: true },
  ]
})

/**
 *
 * custom area
 *
 * */

</script>

<style scoped>
.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}
</style>
